//app.js
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  
  onShow: function(){
	  this.guid();
  },
  
  globalData: {
    userInfo: null,
	domain: 'http://local.app.queue.com/'
  },
  
  getHeader: function (){
	var guid = wx.getStorageSync('guid');
	var userToken = wx.getStorageSync('userToken');
	return {'guid':guid, 'userToken': userToken, 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'};
  },
  
  getFormData: function (data) {
	  var d = []
	  var i = 0;
	  for(var k in data){
		  d[i] = k + '=' + data[k]
		  i++;
	  }
	  return d.join('&');
  },
  
  freshToken: function (url) {
	  var api = this.globalData.domain + 'users/user-refresh-token'
	  var ts = this;
	  wx.request({
		  method: 'POST',
	  	  data: ts.getFormData({username: username, password: password}),
	  	  header: ts.getHeader(),
	  	  success (res) {
	  		  var t = res.data;
	  		  if(t.code == 1){
	  		  	  wx.setStorageSync('userToken', t.result.userToken);
	  			  wx.setStorageSync('userRefreshToken', t.result.refreshToken);
	  			  wx.setStorageSync('effective', t.result.effective);
				  var tm = Math.round(new Date().getTime()/1000, 0);
	  			  wx.setStorageSync('effectiveStart', tm);
				  if(url != null && url != ''){
				  	wx.navigateTo({url: url});
				  }
	  		  }
	  	  }
	  })
  },
  
  checkToken: function(url) {
  	var userToken = wx.getStorageSync('userToken');
  	var effective = wx.getStorageSync('effective') - 100;
  	var effectiveStart = wx.getStorageSync('effectiveStart');
  	var tm = Math.round(new Date().getTime() / 1000, 0);
	// var guid = wx.getStorageSync('guid');
	// var uri = (guid == null || guid == '') ? '../index/index' : '../login/login';
  	if (userToken == '' || userToken == null || userToken == false) {
  		wx.reLaunch({url: '../login/login'});
  	} else {
  		if (tm - effectiveStart > effective) {
  			//userToken过期，刷新Token
  			var refreshToken = wx.getStorageSync('userRefreshToken');
  			if (userToken == '' || userToken == null || userToken == false) {
  				wx.reLaunch({url: '../login/login'});
  			} else {
  				this.freshToken(url)
  			}
  		} else {
			if(url != null && url != ''){
				wx.redirectTo({url: url});
			}
  		}
  	}
  },
  
  guid: function() {
		var guid = wx.getStorageSync('guid')
		if (guid == '') {
			var ts = this;
			var api = this.globalData.domain + 'site/guid';
			wx.request({
				url: api,
				method: 'POST',
				data: {},
				header: {},
				success(res) {
					var t = res.data;
					if (t.code == 1) {
						wx.setStorageSync('guid', t.result.guid);
					}
				}
			});
		}
	},
})